package com.canbot.u05.activity.training;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.drawable.AnimationDrawable;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;

import com.alibaba.fastjson.JSON;
import com.canbot.u05.R;
import com.canbot.u05.bean.TrainingTask;
import com.canbot.u05.bean.training.Step;
import com.canbot.u05.view.TrainingEditTextDialog;

import java.util.List;


public class MyCallBack extends ItemTouchHelper.Callback {

        private final Context context;

        private int dragFlags;

        private int swipeFlags;

        private PostArticleImgAdapter adapter;

        private List<TrainingTask> images;

        private TrainingEditTextDialog editTextDialog;

        private SharedPreferences sharedPreferences;

        private String taskname;

        private int adapterPosition;

        private Boolean idDel = false;

        private int res;

        private ImageView dragDelImage;

        private RecyclerView.ViewHolder itemViewHolder;

        private boolean isDelete;

        public void setDelImage(ImageView delImage, int res) {
                this.delImage = delImage;
                this.res = res;
        }

        private ImageView delImage;

        public MyCallBack(PostArticleImgAdapter adapter, List<TrainingTask> images, Context context, SharedPreferences sharedPreferences, String taskName) {
                this.adapter = adapter;
                this.context = context;
                this.images = images;
                this.sharedPreferences = sharedPreferences;
                this.taskname = taskName;
                windowManager = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE));
                editTextDialog = new TrainingEditTextDialog(context, 2);
        }


        /**
         * 设置item是否处理拖拽事件和滑动事件，以及拖拽和滑动操作的方向
         *
         * @param recyclerView
         * @param viewHolder
         * @return
         */
        @Override
        public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
                //判断 recyclerView的布局管理器数据
                if (recyclerView.getLayoutManager() instanceof StaggeredGridLayoutManager) {//设置能拖拽的方向
                        dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
                        swipeFlags = 0;//0则不响应事件
                }
                return makeMovementFlags(dragFlags, swipeFlags);
        }

        /**
         * 当用户从item原来的位置拖动可以拖动的item到新位置的过程中调用
         *
         * @param recyclerView
         * @param viewHolder
         * @param target
         * @return
         */
        @Override
        public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                int fromPosition = viewHolder.getAdapterPosition();//得到item原来的position
                int toPosition = target.getAdapterPosition();//得到目标position
                if (toPosition == images.size() - 1 || images.size() - 1 == fromPosition) {
                        return true;
                }

                String stepList = sharedPreferences.getString(taskname, null);
                List<Step> stepOld = JSON.parseArray(stepList, Step.class);

                //                Step fromStep=stepOld.get(fromPosition);
                //                Step toStep=stepOld.get(toPosition);
                //
                //                stepOld.set(fromPosition,toStep);
                //                stepOld.set(toPosition,fromStep);
                Step removeStep = stepOld.remove(fromPosition);
                stepOld.add(toPosition, removeStep);

                sharedPreferences.edit().putString(taskname, JSON.toJSONString(stepOld)).apply();

                TrainingTask remove = images.remove(fromPosition);
                images.add(toPosition, remove);
                adapter.notifyItemMoved(fromPosition, toPosition);

                return true;
        }

        /**
         * 设置是否支持长按拖拽
         *
         * @return
         */
        @Override
        public boolean isLongPressDragEnabled() {
                return false;
        }

        /**
         * @param viewHolder
         * @param direction
         */
        @Override
        public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {

        }

        /**
         * 当用户与item的交互结束并且item也完成了动画时调用
         *
         * @param recyclerView
         * @param viewHolder
         */
        @Override
        public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
                super.clearView(recyclerView, viewHolder);
                windowManager.removeView(dragImageView);
                windowManager.removeView(dragDelImage);
                viewHolder.itemView.setVisibility(View.VISIBLE);
                delImage.setVisibility(View.VISIBLE);
                if (!idDel) {
                        adapter.notifyDataSetChanged();
                }
        }

        /**
         * 自定义拖动与滑动交互
         *
         * @param c
         * @param recyclerView
         * @param viewHolder
         * @param dX
         * @param dY
         * @param actionState
         * @param isCurrentlyActive
         */
        @Override
        public void onChildDraw(Canvas c, RecyclerView recyclerView, final RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState,
                                boolean isCurrentlyActive) {


                if (actionState == ItemTouchHelper.ACTION_STATE_DRAG) {

                        if (isDelete) {
                                return;
                        }
                        int[] ints = new int[2];
                        int[] ints2 = new int[2];
                        delImage.getLocationOnScreen(ints);
                        int width = delImage.getWidth();
                        int height = delImage.getHeight();
                        int w = viewHolder.itemView.getWidth();
                        int h = viewHolder.itemView.getHeight();
                        viewHolder.itemView.getLocationOnScreen(ints2);
                        layoutParams.x = ints2[0];
                        layoutParams.y = ints2[1];
                        windowManager.updateViewLayout(dragImageView, layoutParams);
                        Rect rect = new Rect(ints2[0], ints2[1], ints2[0] + w * 3 / 4, ints2[1] + h);
                        Log.e("onItemClear", "rect:" + rect);
                        boolean contains = rect.contains(ints[0] + width / 2, ints[1] + height / 2);
                        dragDelImage.setSelected(contains);
                }

                super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
        }

        /**
         * 当长按选中item的时候（拖拽开始的时候）调用
         *
         * @param viewHolder
         * @param actionState
         */
        @Override
        public void onSelectedChanged(final RecyclerView.ViewHolder viewHolder, int actionState) {
                if (actionState == ItemTouchHelper.ACTION_STATE_IDLE) {
                        isDelete = true;
                        int[] ints = new int[2];
                        int[] ints2 = new int[2];
                        delImage.getLocationOnScreen(ints);
                        int width = delImage.getWidth();
                        int height = delImage.getHeight();
                        int w = itemViewHolder.itemView.getWidth();
                        int h = itemViewHolder.itemView.getHeight();
                        itemViewHolder.itemView.getLocationOnScreen(ints2);
                        Rect rect = new Rect(ints2[0], ints2[1], ints2[0] + w * 3 / 4, ints2[1] + h);
                        Log.e("onItemClear", "rect:" + rect);
                        boolean contains = rect.contains(ints[0] + width / 2, ints[1] + height / 2);
                        Log.e("onItemClear", "contains:" + contains);
                        if (contains) {
                                adapterPosition = itemViewHolder.getAdapterPosition();
                                editTextDialog.setTitle("是否删除该步骤任务 ?", "");
                                editTextDialog.setOnNegativeListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View view) {
                                                idDel = false;
                                                editTextDialog.dismiss();
                                                itemViewHolder.itemView.setVisibility(View.VISIBLE);
                                                adapter.notifyDataSetChanged();
                                        }
                                });
                                editTextDialog.setOnPositiveListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View view) {
                                                idDel = false;
                                                editTextDialog.dismiss();
                                                images.remove(adapterPosition);
                                                String stepList = sharedPreferences.getString(taskname, null);
                                                List<Step> stepOld = JSON.parseArray(stepList, Step.class);

                                                stepOld.remove(adapterPosition);

                                                sharedPreferences.edit().putString(taskname, JSON.toJSONString(stepOld)).apply();

                                                //                                                adapter.notifyItemRemoved(adapterPosition);
                                                adapter.notifyDataSetChanged();
                                        }
                                });

                                editTextDialog.show();
                                idDel = true;
                                return;
                        }
                }
                if (actionState != ItemTouchHelper.ACTION_STATE_IDLE) {
                        isDelete = false;
                        if (viewHolder instanceof PostArticleImgAdapter.MyViewHolder) {
                                //让ViewHolder知道Item开始选中
                                itemViewHolder = viewHolder;
                        }
                }
                super.onSelectedChanged(viewHolder, actionState);
        }


        private WindowManager windowManager;

        private WindowManager.LayoutParams layoutParams;

        private ImageView dragImageView;

        public void showWindowView(View itemView) {
                itemView.setDrawingCacheEnabled(true);
                Bitmap drawingCache = itemView.getDrawingCache();
                layoutParams = new WindowManager.LayoutParams(WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT);
                dragImageView = new ImageView(context);
                dragImageView.setImageBitmap(drawingCache);
                int[] ints = new int[2];
                itemView.getLocationOnScreen(ints);
                layoutParams.x = ints[0];
                layoutParams.y = ints[1];
                layoutParams.width = itemView.getWidth();
                layoutParams.height = itemView.getHeight();
                layoutParams.gravity = Gravity.TOP | Gravity.LEFT;
                layoutParams.format = PixelFormat.TRANSLUCENT;
                layoutParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY;
                layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                                     | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                                     | WindowManager.LayoutParams.FLAG_FULLSCREEN;
                windowManager.addView(dragImageView, layoutParams);
                itemView.setVisibility(View.INVISIBLE);
                addDel(delImage);
        }


        private void addDel(ImageView imageView) {
                imageView.setDrawingCacheEnabled(true);
                WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams(WindowManager.LayoutParams.WRAP_CONTENT,
                                                                                         WindowManager.LayoutParams.WRAP_CONTENT);
                dragDelImage = new ImageView(context);
                dragDelImage.setImageResource(res);
                int[] ints = new int[2];
                imageView.getLocationOnScreen(ints);
                layoutParams.x = ints[0];
                layoutParams.y = ints[1];
                layoutParams.width = imageView.getWidth();
                layoutParams.height = imageView.getHeight();
                layoutParams.gravity = Gravity.TOP | Gravity.LEFT;
                layoutParams.format = PixelFormat.TRANSLUCENT;
                layoutParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY;
                layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                                     | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                                     | WindowManager.LayoutParams.FLAG_FULLSCREEN;
                windowManager.addView(dragDelImage, layoutParams);
                imageView.setVisibility(View.INVISIBLE);
        }

}
